package com.spider.gp.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spider.gp.constant.UrlConstant;
import com.spider.gp.dao.*;
import com.spider.gp.processor.*;

import com.spider.gp.util.DataUtil;
import com.spider.gp.util.HttpUtil;
import com.spider.gp.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.utils.HttpConstant;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * description:
 *
 * @author clare
 * @date 2022/05/20 08:49
 **/
@Controller
@Slf4j
public class SpriderController {
    @Autowired
    private LonghubangProcessor longhubangProcessor;
    @Autowired
    private HangyeProcessor hangyeProcessor;

    @Autowired
    private LianbanProcessor lianbanProcessor;
    @Autowired
    private DieTingProcessor dieTingProcessor;
    @Autowired
    private GpHyProcessor gpHyProcessor;
    @Autowired
    private HyProcessor hyProcessor;
    @Autowired
    private ZhishuProcessor zhishuProcessor;
    @Autowired
    private GpPrePriceProcessor liianbanGpProcessor;
    @Autowired
    private GpInfoProcessor gpInfoProcessor;
    @Autowired
    private ZRZTProcessor zRZTProcessor;
    @Autowired
    private KuaiLeProcessor kuaiLeProcessor;
    @Autowired
    private HyDao hyDao;
    @Autowired
    private GpHyDao gpHyDao;
    @Autowired
    private HignLowProcessor hignLowProcessor;
    @Autowired
    private GpDetailProcessor gpDetailProcessor;
    @Autowired
    private LowHighDao lowHighDao;
    @Autowired
    private LowHighTjDao lowHighTjDao;
    @Autowired
    private GpDetailDao gpDetailDao;





    /**
     * 更新股票价格
     * @param code
     * @param remark
     */
    public void gpDetail(String code, String remark) {
        try {
            if (code.equals("000001") && remark.equals("1")) {
                code = "1000001";
            }
            if (code.equals("399001") && remark.equals("0")) {
                code = "0399001";
            }
            //0.300803&beg=20201202&end=20500000
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
            String reportTime = formatter.format(new Date());
            LambdaQueryWrapper<GpDetail> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(GpDetail::getCode, code);
            GpDetail gpDetail = gpDetailDao.selectOne(wrapper);

//            LocalDate localDate= LocalDate.parse(lowHigh.getReportTime(), DateTimeFormatter.ofPattern("yyyyMMdd"));
//            localDate = localDate.minusMonths(1).with(TemporalAdjusters.lastDayOfMonth());
//            String timeL = localDate.toString().substring(0, 7).replace("-", "")+"01";

            Request request = new Request();
            String startTime = "20220101";
            String startTimeTom = "20220101";


            if (gpDetail != null) {
                String[] split = gpDetail.getDetail().split(";");
                String lsTime = split[split.length - 1].split(",")[0];
                Date whyt = DataUtil.subtractTime(DataUtil.getDateFromStr(lsTime, "yyyy-MM-dd"), 1);
                startTimeTom = DataUtil.getStrFromDate(whyt , "yyyyMMdd");
                startTime = gpDetail.getReportTime();
            }
            if (reportTime.equals(startTime)){
                return;
            }
            request.setMethod(HttpConstant.Method.GET);
            if (code.equals("1000001")) {
                code = "000001";
            }
            if (code.equals("0399001")) {
                code = "399001";
            }

            request.setUrl(UrlConstant.HighLow + remark + "." + code + "&beg=" + startTimeTom + "&end=" + reportTime);

            Spider.create(gpDetailProcessor).addRequest(request).run();
        } catch (Exception e) {
            log.error("更新股票价格失败： " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        System.out.println("20230316".compareTo("20230418"));
    }


    public void hignLow(String code, String remark) {
        try {
            if (code.equals("000001") && remark.equals("1")) {
                code = "1000001";
            }
            if (code.equals("399001") && remark.equals("0")) {
                code = "0399001";
            }
            //0.300803&beg=20201202&end=20500000
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
            String reportTime = formatter.format(new Date());
            LambdaQueryWrapper<LowHigh> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(LowHigh::getCode, code);
            LowHigh lowHigh = lowHighDao.selectOne(wrapper);

//            LocalDate localDate= LocalDate.parse(lowHigh.getReportTime(), DateTimeFormatter.ofPattern("yyyyMMdd"));
//            localDate = localDate.minusMonths(1).with(TemporalAdjusters.lastDayOfMonth());
//            String timeL = localDate.toString().substring(0, 7).replace("-", "")+"01";

            Request request = new Request();
            String startTime = "20190101";


            if (lowHigh != null) {
                String highPoint = lowHigh.getHighPoint();
                String lowPoint = lowHigh.getLowPoint();
                String[] highs = highPoint.split(";");
                String[] lows = lowPoint.split(";");
                String high = highs[highs.length - 1];
                String low = lows[lows.length - 1];
                String[] highTime = high.split(",");
                String[] lowTime = low.split(",");
                if (highTime[0].compareTo(lowTime[0]) >= 0) {
                    startTime = highTime[0];
                } else {
                    startTime = lowTime[0];
                }
            }
            request.setMethod(HttpConstant.Method.GET);
            if (code.equals("1000001")) {
                code = "000001";
            }
            if (code.equals("0399001")) {
                code = "399001";
            }
            request.setUrl(UrlConstant.HighLow + remark + "." + code + "&beg=" + startTime + "&end=" + reportTime);

            Spider.create(hignLowProcessor).addRequest(request).run();
            System.out.println();
        } catch (Exception e) {
            log.error("高低点失败： " + e.getMessage());
        }
    }


    public void kuaile8() {
        try {
            Request request = new Request();
            request.setUrl(UrlConstant.KUAI_LE_8);
            request.setMethod(HttpConstant.Method.GET);
            request.addHeader("Referer", "https://www.zhcw.com/");
            Spider.create(kuaiLeProcessor).addRequest(request).run();
            System.out.println();
        } catch (Exception e) {
            log.error("快乐八爬虫失败： " + e.getMessage());
        }
    }

    public void longHuBang() {
        try {
            Spider.create(longhubangProcessor).addUrl(UrlConstant.THS_LONG_HU_BANG).run();
        } catch (Exception e) {
            log.error("龙虎榜爬虫失败： " + e.getMessage());
        }
    }

    public void hangYe() {
        try {
            Spider.create(hangyeProcessor).addUrl(UrlConstant.DFCF_HANG_YE_ZF).addUrl(UrlConstant.DFCF_HANG_YE_DF).addUrl(UrlConstant.DFCF_GAI_NIAN_HANG_YE_ZF).addUrl(UrlConstant.DFCF_GAI_NIAN_HANG_YE_DF).run();
        } catch (Exception e) {
            log.error("行业爬虫失败： " + e.getMessage());
        }

    }

    public void zhiShu() {
        try {
            Spider.create(zhishuProcessor).addUrl(UrlConstant.DFCF_ZHI_SHU).run();
        } catch (Exception e) {
            log.error("指数爬虫失败： " + e.getMessage());
        }
    }

    public void lianBan(String reportTime) {
        try {
//            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
//            String reportTime = formatter.format(new Date());
//            String reportTime = "20220801";
            String url = UrlConstant.DFCF_LB + reportTime;
            Spider.create(lianbanProcessor).addUrl(url).run();
        } catch (Exception e) {
            log.error("连板爬虫失败： " + e.getMessage());
        }
    }


    public void lianBanGp() {
        try {

            //每日妖股  只记录4板以及4版以上的。
            String url = UrlConstant.DFCF_GG + "lmt=5&secid=0.300059";

            Spider.create(liianbanGpProcessor).addUrl(url).run();
        } catch (Exception e) {
            log.error("连板股票爬虫失败： " + e.getMessage());
        }
    }

    /**
     * 股票基本信息
     */

    public void gpInfo() {
        try {
            Spider.create(gpInfoProcessor).addUrl(UrlConstant.DFCF_GG_ALL_INFO).run();
        } catch (Exception e) {
            log.error("连板股票爬虫失败： " + e.getMessage());
        }
    }


    /**
     * 昨日涨停-含一字板
     */

    public void zrzt(String reportTime) {
        try {
            String url = UrlConstant.DFCF_ZR_LB_ZS_LS + reportTime;
            String url01 = UrlConstant.DFCF_ZR_ZT_ZS_LS + reportTime;
            Spider.create(zRZTProcessor).addUrl(url).addUrl(url01).run();
        } catch (Exception e) {
            log.error("连板股票爬虫失败： " + e.getMessage());
        }
    }


    /**
     * 跌停池
     */

    public void dtc(String reportTime) {
        try {
//            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
//            String reportTime = formatter.format(new Date());
//            String reportTime = "20220801";
            String url = UrlConstant.DFCF_DTC_JR + reportTime;
            Spider.create(dieTingProcessor).addUrl(url).run();
        } catch (Exception e) {
            log.error("连板股票爬虫失败： " + e.getMessage());
        }
    }


    /**
     * 所有行业内所属股票
     */
    public void gpHyAll(String code) {
        try {
            LambdaQueryWrapper<GpHy> objectLambdaQueryWrapper = new LambdaQueryWrapper<>();
            objectLambdaQueryWrapper.eq(Strings.isNotBlank(code), GpHy::getCode, code);
            //删除全部
            int delete = gpHyDao.delete(objectLambdaQueryWrapper);
            //查询所有
            if (Strings.isBlank(code)) {
                List<Hy> hies = hyDao.selectList(new LambdaQueryWrapper<>());
                hies.forEach(a -> {
                    if (a.getName().contains("昨日") || a.getName().contains("一字板") || a.getName().contains("板块") || a.getName().contains("次新")
                            || a.getName().contains("上证") || a.getName().contains("深") || a.getName().contains("三板") || a.getName().contains("低价股")
                            || a.getName().contains("ST股") || a.getName().contains("内蒙古") || a.getName().contains("富时罗素") || a.getName().contains("成渝特区")
                            || a.getName().contains("参股") || a.getName().contains("MSCI") || a.getName().contains("标准") || a.getName().contains("创业板")
                            || a.getName().contains("北交所概念") || a.getName().contains("黑龙江") || a.getName().contains("AB股") || a.getName().contains("AH股") || a.getName().contains("HS300")
                            || a.getName().contains("重仓") || a.getName().contains("融资融券") || a.getName().contains("央视") || a.getName().contains("B股") || a.getName().contains("创业成份")
                            || a.getName().contains("中证") || a.getName().contains("沪股通") || a.getName().contains("中证") || a.getName().contains("送转")
                    ) {
                        return;
                    }
                    String url = UrlConstant.DFCF_BK_SYGP + a.getCode();
                    Spider.create(gpHyProcessor).addUrl(url).run();
                    //休息一下子 精力更长足
//                    try { TimeUnit.MILLISECONDS.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); }
                });
            } else {
                String url = UrlConstant.DFCF_BK_SYGP + code;
                Spider.create(gpHyProcessor).addUrl(url).run();
            }


        } catch (Exception e) {
            log.error("连板股票爬虫失败： " + e.getMessage());
        }
    }

    /**
     * 所有行业
     */
    public void hyAll() {
        try {
            Spider.create(hyProcessor).addUrl(UrlConstant.DFCF_SYBK).run();
        } catch (Exception e) {
            log.error("板块爬虫失败： " + e.getMessage());
        }
    }
}








